package com.python.listener.core;

import com.python.listener.Exception.CustomException;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;

/**
 * 建立socket连接的对象
 *
 * @author zt
 */
public final class ChannelSocketWrite {

    private static String hostName;
    private static int port;

    public static void init(String hostName, int port) {
        ChannelSocketWrite.hostName = hostName;
        ChannelSocketWrite.port = port;
    }

    public static String call(String requestInfo) {
        try (SocketChannel socketChannel = SocketChannel.open()) {
            socketChannel.configureBlocking(false);
            socketChannel.connect(new InetSocketAddress(hostName, port));
            ByteBuffer buf = ByteBuffer.allocate(1024);
            buf.clear();
            while (!socketChannel.finishConnect()) {
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    Thread.currentThread().interrupt();
                }
            }
            buf.put(requestInfo.getBytes(StandardCharsets.UTF_8));
            buf.flip();
            socketChannel.write(buf);
            buf.clear();
            int numBytesRead;
            while ((numBytesRead = socketChannel.read(buf)) != -1) {
                if (numBytesRead == 0) {
                    try {
                        Thread.sleep(1);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                        Thread.currentThread().interrupt();
                    }
                    continue;
                }
                buf.flip();
                StringBuffer result = new StringBuffer();
                byte[] buff = new byte[1024];
                while (buf.hasRemaining()) {
                    buf.get(buff, 0, numBytesRead);
                    result.append(new String(buff, 0, numBytesRead, StandardCharsets.UTF_8));
                }
                return result.toString();
            }
            throw new CustomException("未获取到调用返回值");
        } catch (IOException e) {
            e.printStackTrace();
            throw new CustomException("调用python时io异常");
        }
    }
}
